package com.dengjk.codegenerator.controller;

import com.dengjk.codegenerator.common.constants.SystemContants;
import com.dengjk.codegenerator.dao.UserInfoDao;
import com.dengjk.codegenerator.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * Created by dengjk on 2017/1/14.
 */
@Controller
public class LoginController extends BaseController {


    @Autowired
    private UserInfoDao userInfoDao;


    /**
     * 跳转 首页
     *
     * @return
     */
    @GetMapping("/")
    public String homePage(HttpServletResponse response) throws IOException {
        return "/views/index/index";
    }


    /**
     * 跳转登录页面
     *
     * @return
     */
    @GetMapping(value = "/login")
    public ModelAndView toLogin() {
        // 3、将命令对象传入业务对象进行业务处理
        ModelAndView mv = new ModelAndView();
        // 添加模型数据 可以是任意的POJO对象
        mv.addObject("message", "welcome login repal.com");
        // 设置逻辑视图名，视图解析器会根据该名字解析到具体的视图页面
        mv.setViewName("/views/index/login");
        return mv;
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public boolean login(String username, String password) {
        UserInfo userInfo = userInfoDao.findFirstByNameAndPassword(username, password);
        if (userInfo != null) {
            request.getSession().setAttribute(SystemContants.CODEUSER, userInfo);
            request.getSession().setMaxInactiveInterval(3600 * 12);
            return true;
        }
        return false;
    }

    /**
     * 登出
     *
     * @return
     */
    @GetMapping("/logout")
    public String logout() {
        request.getSession().invalidate();
        return "redirect:/login";
    }

}
